package com.ifcar.app.activity;

import java.io.BufferedInputStream;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;

import net.oauth.OAuthAccessor;

import org.apache.http.HttpHost;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.conn.params.ConnRoutePNames;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;
import org.json.JSONArray;
import org.json.JSONObject;

import t4j.TBlog;
import t4j.TBlogException;
import weibo4android.Weibo;
import weibo4android.http.ImageItem;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.preference.PreferenceManager;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.view.inputmethod.InputMethodManager;
import android.webkit.CookieManager;
import android.webkit.CookieSyncManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.ifcar.app.db.NewsSQLiteOpenHelper;
import com.ifcar.app.util.HttpUtils;
import com.ifcar.app.util.Logger;
import com.ifcar.app.util.MyToast;
import com.ifcar.app.util.PicUtil;
import com.ifcar.app.util.StringUtil;
import com.ifcar.app.util.ThemeSettingsHelper;
import com.ifcar.app.util.Tools;
import com.ifcar.app.weibo.OAuthHelper;
import com.ifcar.app.weibo.QWeiboSyncApi;
import com.ifcar.app.weibo.WeiboLogin;
import com.ifcar.app.weibo.YdNoteLoginHelper;
import com.ifcar.app.weibo.QWeiboType.ResultType;
import com.ifcar.app.activity.R;
import com.renren.api.connect.android.Renren;
import com.renren.api.connect.android.exception.RenrenException;
import com.renren.api.connect.android.share.ShareSetRequestParam;
import com.renren.api.connect.android.share.ShareSetResponseBean;

public class ShareToMicroBlog extends BaseActivity{
	
	private EditText edit_postmessage;
	private Button do_postmicroblog_button;
	private String message = "";
	private String messageyd = "";
	private String cookie="";
	private String picurl="";
	private SharedPreferences set_prefs;
	private String sharetitle="";//分享的内容
	private String sharetitleyd;
	private String shareurl = "";
	private boolean tie = false;
	private boolean ispic = false;
	private boolean sharefloor = false;
	private boolean microhot;
    private String board = "";
    private String postid = "";
    private String pnum = "";
	private String seturl = "";
	private String shareimg;
	private int sharetype = -1;
	private RelativeLayout descLayout;
	private TextView accountInfo;
	private TextView leave_size;
	private String token;
	private String tokenSecret;
	private boolean isBindAccount = false;
	private String imgname = "";
	private ImageView share_photo_img;
	private TextView leave_size3;
	private TextView share_wb_title;
	private String shareend = "";//@网易新闻客户端
	private Renren mRenren;
	private int limit1 = 163;
	private int limit2 = 140;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		setContentView(R.layout.sharetomicroblog);
		findViewsById();
		do_postmicroblog_button.setEnabled(false);
		setListener();
		Bundle bundle = this.getIntent().getExtras();
		mRenren = new Renren(WeiboLogin.RENREN_API_KEY, WeiboLogin.RENREN_SECRET_KEY, WeiboLogin.RENREN_APP_ID, this);
		set_prefs = PreferenceManager.getDefaultSharedPreferences(this);
		
		cookie = set_prefs.getString("cookie", "0");
		
		if(null!=bundle){
			sharetitle = bundle.getString("sharetitle");
			sharetitleyd = bundle.getString("sharetitleyd");
			shareurl = bundle.getString("shareurl");
			tie = bundle.getBoolean("tie");
			ispic = bundle.getBoolean("ispic");
			seturl = bundle.getString("seturl");
			shareimg = bundle.getString("shareimg");
			
			sharefloor = bundle.getBoolean("sharefloor");
			board = bundle.getString("board");
			postid = bundle.getString("postid");
			pnum = bundle.getString("pnum");
			
			sharetype  = bundle.getInt("sharetype");
			imgname = bundle.getString("imgname");
			microhot = bundle.getBoolean("microhot", false);
			
		}
		
		if(null!=sharetitle){
			sharetitle = sharetitle.replace("原文：", "");
		}
		if(null!=sharetitleyd){
			sharetitleyd = sharetitleyd.replace("原文：", "");
		}
		
		if(ispic){
			if(sharetype==4){
				messageyd = "//分享网易图集:"+sharetitle+" ";
				message = "//分享网易图集:"+sharetitleyd+" ";
			}else{
				message = "//分享网易图集:"+sharetitle+" ";
			}
		}else if(tie){
			if(sharetype==4){
				messageyd = "//分享网易跟贴:"+sharetitle+" ";
				message = "//分享网易跟贴:"+sharetitleyd+" ";
			}else{
				message = "//分享网易跟贴:"+sharetitle+" ";
			}
		}else if(sharefloor){
			if(sharetype==4){
				messageyd = "//分享网易跟贴:"+sharetitle+" ";
				message = "//分享网易跟贴:"+sharetitleyd+" ";
			}else{
				message = "//分享网易跟贴:"+sharetitle+" ";
			}
		}else if(microhot){
			message = "//"+sharetitle+" ";
		}else{
			if(sharetype==4){
				messageyd = "//分享网易新闻:"+sharetitle+" ";
				message = "//分享网易新闻:"+sharetitleyd+" ";
			}else{
				message = "//分享网易新闻:"+sharetitle+" ";
			}
		}
		InputMethodManager imm = (InputMethodManager)getSystemService(INPUT_METHOD_SERVICE);
		imm.showSoftInput(edit_postmessage, 0);
		if (null != shareurl && !"".equals(shareurl)) {//优先处理图片
			
		    Integer shortlenght = 20;
            
            if(sharetype==3){//人人网特殊处理
                
            }else{
                if(ispic){
                    if(sharetype!=4){
                        shortlenght = 40;
                    }
                }else if(sharefloor){
                    
                    if(sharetype!=4){
                        shortlenght = 40;
                    }
                }else{
                    
                    if(sharetype!=4){
                        if(null!=shareimg && !"".equals(shareimg) && sharetype == 0){
                            shortlenght = 40;
                        }
                    }
                }
            }
            
            limit1 = limit1 - shortlenght;
            limit2 = limit2 - shortlenght;
		}
		
		reflashormoreDataHandler.sendEmptyMessage(3);
		new Thread(){
            public void run(){
                reflashormoreDataHandler.sendEmptyMessage(6);
            }
        }.start();
        
        if(sharetype == 4){
        	leave_size.setVisibility(View.INVISIBLE);
        	leave_size3.setVisibility(View.INVISIBLE);
        	findViewById(R.id.account_info).setVisibility(View.INVISIBLE);
        	findViewById(R.id.leave_size1).setVisibility(View.INVISIBLE);
        }
	}
	
	public String  getShortUrl(){
	    
	    String rst = "";
        
	    if (null != shareurl && !"".equals(shareurl)) {
	        if(sharetype==3){//人人网特殊处理
	            if(ispic){
	                String shortseturl = HttpUtils.getDocShortUrl("www", seturl,ShareToMicroBlog.this);
	                rst = shortseturl; 
	            }else if(sharefloor){                           
	                rst = HttpUtils.getDocShortUrl("www", shareurl,ShareToMicroBlog.this);                            
	            }else{
	                rst = HttpUtils.getDocShortUrl("www", shareurl,ShareToMicroBlog.this);
	            }
	        }else{
	            if(ispic){
	                rst = HttpUtils.getImageShortUrl(shareurl,ShareToMicroBlog.this);
	                String shortseturl = HttpUtils.getDocShortUrl("www", seturl,ShareToMicroBlog.this);
	                if(sharetype==4){
	                    StringBuilder html = new StringBuilder();
	                    html.append("图集地址：<a href='").append(seturl).append("'>").append(seturl).append("</a>").append("\t")
	                        .append("<br/>图片：<img src='").append(rst).append("' />");
	                    rst = html.toString();
	                }else{
	                    rst = rst + " "+shortseturl;
	                }
	            }else if(sharefloor){
	                
	                rst = HttpUtils.getDocShortUrl("www", shareurl,ShareToMicroBlog.this);
	                String shorturl = HttpUtils.getResponseFromGetUrl(StringUtil.TIEFLOORSHORTURL+board+"/"+postid+"/"+pnum+".html", 6000,ShareToMicroBlog.this);
	                    
	                if(sharetype == 4){
	                    StringBuilder html = new StringBuilder();
	                    html.append("跟贴地址：<a href='").append(rst).append("'>").append(rst).append("</a>")
	                        .append("<br/>跟贴楼层截图：<img src='").append(shorturl).append("' />");
	                    rst = html.toString();
	                }else{
	                    rst = rst + " " + shorturl; 
	                }
	            }else if(microhot){
	                
	                rst = HttpUtils.getDocShortUrl("www", shareurl,ShareToMicroBlog.this);
	                String imgs = "";
	                if(null!=shareimg && !"".equals(shareimg) && sharetype == 0){ 
	                    imgs = HttpUtils.getImageShortUrl(shareimg,ShareToMicroBlog.this);
	                }
	                
	                if(!"".equals(imgs)){
	                    rst = rst + " " + imgs;
	                }
	            } else {
	            	rst = HttpUtils.getDocShortUrl("www", shareurl,ShareToMicroBlog.this);
	                String imgs = "";
	                if(null!=shareimg && !"".equals(shareimg) && sharetype == 0){ 
	                    imgs = HttpUtils.getImageShortUrl(shareimg,ShareToMicroBlog.this);
	                }
	                if(sharetype==4){
	                    StringBuilder html = new StringBuilder();
	                    html.append("PC查看地址：<a href='").append(rst).append("'>").append(rst).append("</a>");
	                    if(!"".equals(imgs)){
	                        html.append("<img src='").append(imgs).append("'/>");
	                    }
	                    rst = html.toString();
	                }else{
	                    if(!"".equals(imgs))
	                        rst = rst + " " + imgs;
	                }
	            }
	        }
	    }
        
        
        return rst;
	}
	
	private void initAccount(){
		
        String sql = "";
        
        if(sharetype == 0) {
            
        	share_wb_title.setText((microhot ? "转发" : "分享") + "到网易微博");
            
            sql = "select * from " + NewsSQLiteOpenHelper.OAUTH_TABLE + " where " 
                + NewsSQLiteOpenHelper.OAUTH_TYPE + "='netease'";

            Cursor cursor = db.rawQuery(sql, new String[]{});
            if(cursor != null && cursor.getCount()!= 0 ) { 
                cursor.moveToFirst();
                token = cursor.getString(cursor.getColumnIndex(NewsSQLiteOpenHelper.OAUTH_TOKEN));
                tokenSecret = cursor.getString(cursor.getColumnIndex(NewsSQLiteOpenHelper.OAUTH_TOKEN_SECRET));
                String name = cursor.getString(cursor.getColumnIndex(NewsSQLiteOpenHelper.OAUTH_NAME));
                isBindAccount = true;
                if(name != null && !name.equals("")){
                    accountInfo.setText(name+" [@网易]");
                }
                else{
                    accountInfo.setText("已绑定帐号"+" [@网易]");
                }
                
            } else {
                isBindAccount = false;
                accountInfo.setText("尚未绑定帐号");
            }
            if(cursor != null) cursor.close();
            
            if(imgname != null && !imgname.equals("")) share_photo_img.setVisibility(View.VISIBLE);
            else share_photo_img.setVisibility(View.GONE);
            
           
            
        } else if(sharetype == 1){
            
        	share_wb_title.setText((microhot ? "转发" : "分享") + "到新浪微博");
            sql = "select * from " + NewsSQLiteOpenHelper.OAUTH_TABLE + " where " 
                + NewsSQLiteOpenHelper.OAUTH_TYPE + "='sina'";

            Cursor cursor = db.rawQuery(sql, new String[]{});
            if(cursor != null && cursor.getCount()!= 0 ) { 
                cursor.moveToFirst();
                token = cursor.getString(cursor.getColumnIndex(NewsSQLiteOpenHelper.OAUTH_TOKEN));
                tokenSecret = cursor.getString(cursor.getColumnIndex(NewsSQLiteOpenHelper.OAUTH_TOKEN_SECRET));
                String name = cursor.getString(cursor.getColumnIndex(NewsSQLiteOpenHelper.OAUTH_NAME));
                isBindAccount = true;
                if(name != null && !name.equals("")){
                    accountInfo.setText(name+" [@新浪]");
                }
                else{
                    accountInfo.setText("已绑定帐号"+" [@新浪]");
                }
            } else {
                isBindAccount = false;
                accountInfo.setText("尚未绑定帐号");
            }
            if(cursor != null) cursor.close();
            
            if(imgname != null && !imgname.equals("")) share_photo_img.setVisibility(View.VISIBLE);
            else share_photo_img.setVisibility(View.GONE);
            
        
            
        } else if(sharetype == 2) {
        	share_wb_title.setText((microhot ? "转发" : "分享") + "到腾讯微博");
            sql = "select * from " + NewsSQLiteOpenHelper.OAUTH_TABLE + " where " 
            + NewsSQLiteOpenHelper.OAUTH_TYPE + "='qq'";

            Cursor cursor = db.rawQuery(sql, new String[]{});
            if(cursor != null && cursor.getCount()!= 0 ) { 
                cursor.moveToFirst();
                token = cursor.getString(cursor.getColumnIndex(NewsSQLiteOpenHelper.OAUTH_TOKEN));
                tokenSecret = cursor.getString(cursor.getColumnIndex(NewsSQLiteOpenHelper.OAUTH_TOKEN_SECRET));
                String name = cursor.getString(cursor.getColumnIndex(NewsSQLiteOpenHelper.OAUTH_NAME));

                isBindAccount = true;
                if(name != null && !name.equals("")) accountInfo.setText(name+" [@腾讯]");
                else accountInfo.setText("已绑定帐号"+" [@腾讯]");
            } else {
                isBindAccount = false;
                accountInfo.setText("尚未绑定帐号");
            }
           if(cursor != null) cursor.close();

           if(imgname != null && !imgname.equals("")) share_photo_img.setVisibility(View.VISIBLE);
           else share_photo_img.setVisibility(View.GONE);
           
        }else if(sharetype == 3){//分享到人人网

            share_wb_title.setText("分享到人人网");
            sql = "select * from " + NewsSQLiteOpenHelper.OAUTH_TABLE + " where " 
                + NewsSQLiteOpenHelper.OAUTH_TYPE + "='renren'";

            Cursor cursor = db.rawQuery(sql, new String[]{});
            if(cursor != null && cursor.getCount()!= 0 ) { 
                cursor.moveToFirst();
                token = cursor.getString(cursor.getColumnIndex(NewsSQLiteOpenHelper.OAUTH_TOKEN));
                tokenSecret = cursor.getString(cursor.getColumnIndex(NewsSQLiteOpenHelper.OAUTH_TOKEN_SECRET));
                String name = cursor.getString(cursor.getColumnIndex(NewsSQLiteOpenHelper.OAUTH_NAME));
                isBindAccount = true;
                if(name != null && !name.equals("")){
                    accountInfo.setText(name+" [@人人网]");
                }
                else{
                    accountInfo.setText("已绑定帐号"+" [@人人网]");
                }
                
            } else {
                isBindAccount = false;
                accountInfo.setText("尚未绑定帐号");
            }
            if(cursor != null) cursor.close();
            
            if(imgname != null && !imgname.equals("")){
                share_photo_img.setVisibility(View.VISIBLE);
            }else{
                share_photo_img.setVisibility(View.GONE);
                if(null!=shareurl && !"".equals(shareurl)){
                    imgname = shareurl;
                }else if(null!=seturl && !"".equals(seturl)){
                    imgname = seturl;
                }
                
            }
            
            
        }else if(sharetype == 4){//分享到有道笔记

            share_wb_title.setText("分享到有道云笔记");
            sql = "select * from " + NewsSQLiteOpenHelper.OAUTH_TABLE + " where " 
                + NewsSQLiteOpenHelper.OAUTH_TYPE + "='ydnote'";

            Cursor cursor = db.rawQuery(sql, new String[]{});
            if(cursor != null && cursor.getCount()!= 0 ) { 
                cursor.moveToFirst();
                token = cursor.getString(cursor.getColumnIndex(NewsSQLiteOpenHelper.OAUTH_TOKEN));
                tokenSecret = cursor.getString(cursor.getColumnIndex(NewsSQLiteOpenHelper.OAUTH_TOKEN_SECRET));
                String name = cursor.getString(cursor.getColumnIndex(NewsSQLiteOpenHelper.OAUTH_NAME));
                isBindAccount = true;
                if(name != null && !name.equals("")){
                    accountInfo.setText(name+" [@有道云笔记]");
                }
                else{
                    accountInfo.setText("已绑定帐号"+" [@有道云笔记]");
                }
                
            } else {
                isBindAccount = false;
                accountInfo.setText("尚未绑定帐号");
            }
            if(cursor != null) cursor.close();
            
            if(imgname != null && !imgname.equals("")){
                share_photo_img.setVisibility(View.VISIBLE);
            }else{
                share_photo_img.setVisibility(View.GONE);
                if(null!=shareurl && !"".equals(shareurl)){
                    imgname = shareurl;
                }else if(null!=seturl && !"".equals(seturl)){
                    imgname = seturl;
                }
                
            }
            
        }
    
	}
	
	protected void onActivityResult(int requestCode, int resultCode, Intent data)
    {
        super.onActivityResult(requestCode, resultCode, data);
        
        if(requestCode == 0 && resultCode == Activity.RESULT_OK){
            
            new Thread(){
                public void run(){
                    reflashormoreDataHandler.sendEmptyMessage(6);
                }
            }.start();
        }
    }
	
	@Override
	protected void onResume() {
		// TODO Auto-generated method stub
		super.onResume();
	}



	/** 初始化注册View组件 */
	private void findViewsById() {
		share_wb_title = (TextView) findViewById(R.id.share_wb_title);
		edit_postmessage = (EditText) findViewById(R.id.edit_postmessage);
		do_postmicroblog_button = (Button) findViewById(R.id.do_postmicroblog_button);
		descLayout = (RelativeLayout) findViewById(R.id.share_editbox_desc);
		accountInfo = (TextView) descLayout.findViewById(R.id.account_info);
		leave_size = (TextView) descLayout.findViewById(R.id.leave_size2);
		leave_size3 = (TextView) descLayout.findViewById(R.id.leave_size3);
		share_photo_img = (ImageView) descLayout.findViewById(R.id.share_photo_img);
	}
	
	/** 设置监听器 */
	private void setListener() {
		do_postmicroblog_button.setOnClickListener(postmessageListener);
		if(sharetype!=3){//人人网分享除外
		    edit_postmessage.addTextChangedListener(new TextWatcher() {
	            private CharSequence temp;              
	            private int length = 0;
	            
	            @Override
	            public void afterTextChanged(Editable arg0) {
	                // TODO Auto-generated method stub
	                
	            }

	            @Override
	            public void beforeTextChanged(CharSequence arg0, int arg1,
	                    int arg2, int arg3) {
	                // TODO Auto-generated method stub
	                temp = arg0;
	            }

	            @Override
	            public void onTextChanged(CharSequence arg0, int arg1, int arg2,
	                    int arg3) {
	                // TODO Auto-generated method stub
	                
	                if(sharetype == 0) {
	                    length = limit1-temp.length();
	                } else {
	                    length = limit2-temp.length();
	                }
	                if(length < 0) {
	                    leave_size3.setText("已超出");
	                    leave_size.setText(String.valueOf(length*-1));
	                } else {
	                    leave_size3.setText("还可输入");
	                    leave_size.setText(String.valueOf(length));
	                }
	                
	            }
	            
	        });
		}
		
	}
	
	/** 提交Button Listener */
	private OnClickListener postmessageListener = new OnClickListener() {
		
		@Override
		public void onClick(View v) {
			do_postmicroblog_button.setEnabled(false);
			
			if(!Tools.CheckNetwork(ShareToMicroBlog.this)){
			    MyToast.makeText(app, "未检出到可用网络，分享失败！", MyToast.LENGTH_SHORT).show();
			    do_postmicroblog_button.setEnabled(true);
			    return;
			}
			message = edit_postmessage.getText().toString();
			
			if(null != message && !"".equals(message.trim())){
				int length = 0;
				if(sharetype == 4){
					
				}else if(sharetype!=3){
				    if(sharetype == 0) {
	                    length = limit1-message.length();
	                } else {
	                    length = limit2-message.length();
	                }
				}
				
				if(length < 0) {
					
					MyToast.makeText(app, "分享内容已超出字数限制", MyToast.LENGTH_SHORT).show();
					do_postmicroblog_button.setEnabled(true);
				}
				else {
				    
				    if(!isBindAccount){
				        CookieSyncManager.createInstance(ShareToMicroBlog.this);
                        CookieManager cookieManager = CookieManager.getInstance(); 
                        cookieManager.removeAllCookie();
				    }
				    
					 if(sharetype == 0){ // 网易微博

						if(isBindAccount) {
							postEditMessage4netease pe = new postEditMessage4netease(message, token, tokenSecret, imgname);
							pe.start();
							setDefaultTips();
							ShareToMicroBlog.this.finish();
						} else {
							
							MyToast.makeText(app, "请绑定您的帐号", MyToast.LENGTH_SHORT).show();
							Intent intent = new Intent(ShareToMicroBlog.this, WeiboLogin.class);
	                        intent.putExtra("weibo_type", 2);
	                        startActivityForResult(intent,0);
				        	do_postmicroblog_button.setEnabled(true);
						}
						
					} else if(sharetype == 1) { // 新浪微博
                        if(isBindAccount) {
                            postEditMessage4Sina pe = new postEditMessage4Sina(message, token, tokenSecret, imgname);
                            pe.start();
                            setDefaultTips();
                            ShareToMicroBlog.this.finish();
                        } else {
                            
                            MyToast.makeText(app, "请绑定您的帐号", MyToast.LENGTH_SHORT).show();
                            Intent intent = new Intent(ShareToMicroBlog.this, WeiboLogin.class);
                            intent.putExtra("weibo_type", 0);
                            startActivityForResult(intent,0);
                            do_postmicroblog_button.setEnabled(true);
                        }
                    } else if(sharetype == 2) { // qq微博
						if(isBindAccount) {
							postEditMessage4QQ pe = new postEditMessage4QQ(message, token, tokenSecret, imgname);
							pe.start();
							setDefaultTips();
							ShareToMicroBlog.this.finish();
						} else {
							
			                MyToast.makeText(app, "请绑定您的帐号", MyToast.LENGTH_SHORT).show();
                            Intent intent = new Intent(ShareToMicroBlog.this, WeiboLogin.class);
                            intent.putExtra("weibo_type", 1);
                            startActivityForResult(intent,0);
			                do_postmicroblog_button.setEnabled(true);
						}
					}else if(sharetype == 3) { // 人人网
                        if(isBindAccount) {
                            postEditMessage4Renren pe = new postEditMessage4Renren(message, token, tokenSecret, picurl);
                            pe.start();
                            setDefaultTips();
                            ShareToMicroBlog.this.finish();
                        } else {
                            
                            MyToast.makeText(app, "请绑定您的帐号", MyToast.LENGTH_SHORT).show();
                            Intent intent = new Intent(ShareToMicroBlog.this, WeiboLogin.class);
                            intent.putExtra("weibo_type", 3);
                            startActivityForResult(intent,0);
                            do_postmicroblog_button.setEnabled(true);
                        }
                    }else if(sharetype == 4){ // 有道笔记
                    	if(isBindAccount) {
                    		postEditMessage4Ydnote pe =new postEditMessage4Ydnote(sharetitleyd, messageyd, shareurl, token, tokenSecret);
                            pe.start();
                            setDefaultTips();
                            ShareToMicroBlog.this.finish();
                        } else {
                           
                            MyToast.makeText(app, "请绑定您的帐号", MyToast.LENGTH_SHORT).show();
                            Intent intent = new Intent(ShareToMicroBlog.this, WeiboLogin.class);
                            intent.putExtra("weibo_type", 4);
                            startActivityForResult(intent,0);
                            do_postmicroblog_button.setEnabled(true);
                        }
                    }
				}

			}else{				
				new AlertDialog.Builder(ShareToMicroBlog.this)
				.setTitle("分享提示")
				.setMessage("分享内容不能为空")
				.setPositiveButton("确定",
						new DialogInterface.OnClickListener() {
							public void onClick(
									DialogInterface dialoginterface,
									int i) {

								
							}
						}).show();
				
				do_postmicroblog_button.setEnabled(true);
			
			}
			
		}
	};
	
	class postEditMessage extends Thread {

		@Override
		public void run() {
			// TODO Auto-generated method stub
			Message msg = new Message();
			msg.what = 1;
			
			try{
				HttpPost httpRequest = new HttpPost(StringUtil.SHARETOMICROBLOG);
				
				List<NameValuePair> params = new ArrayList<NameValuePair>();
				params.add(new BasicNameValuePair("status", message));
				
				params.add(new BasicNameValuePair("source",StringUtil.NEWSCLIENTSOURCE));
				httpRequest.addHeader("Cookie", cookie);
				// 添加请求参数到请求对象
				httpRequest.setEntity(new UrlEncodedFormEntity(params, HTTP.UTF_8));
		
				DefaultHttpClient httpclient = new DefaultHttpClient();
				Tools.setHttpClientHostProxy(httpclient, ShareToMicroBlog.this);
				HttpResponse httpResponse = httpclient.execute(httpRequest);
				msg.arg1 = 0;
				
			}catch(Exception ex){
				msg.arg1 = 1;
			}
			
			reflashormoreDataHandler.sendMessage(msg);
		}
	}
	
	class postEditMessage4Sina extends Thread {
		private String msg4sina = "";
		private String t = "";
		private String s = "";
		private String img = "";
		public postEditMessage4Sina(String message, String t, String s, String img) {
		    this.msg4sina = message;
			this.t = t;
			this.s = s;
			this.img = img;
		}
		@Override
		public void run() {
			// TODO Auto-generated method stub
			Message msg = new Message();
			msg.what = 1;
			
			Weibo.CONSUMER_KEY = WeiboLogin.sinaCustomKey;
			Weibo.CONSUMER_SECRET = WeiboLogin.sinaCustomSecrect;
	        System.setProperty("weibo4j.oauth.consumerKey", Weibo.CONSUMER_KEY);
	        System.setProperty("weibo4j.oauth.consumerSecret", Weibo.CONSUMER_SECRET);
	        
			try {
			    msg4sina = msg4sina + getShortUrl();
			    this.msg4sina = java.net.URLEncoder.encode(msg4sina, "utf-8");
	        	Weibo weibo = new Weibo();
				weibo.setToken(t, s);
				
				String host = Tools.getHostbyWAP(ShareToMicroBlog.this);
                if(null!=host){
                    weibo.setHttpProxy(host, 80);
                }
				
				if(img != null && !img.equals("") && PicUtil.isLocalPicExit(img)) {
					byte[] content= readFileImage(PicUtil.phototempDir + img);
		        	ImageItem pic=new ImageItem("pic",content);
		        	weibo.uploadStatus(msg4sina, pic);
				} else {
					weibo.updateStatus(msg4sina);
				}
				
				msg.arg1 = 0;
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
				if(e.getMessage().contains("40025")) msg.what = 4;
				else if(e.getMessage().contains("40072")) {
					msg.what = 5;
					msg.arg1 = 0;
				}
				else msg.arg1 = 1;
			}
			
			reflashormoreDataHandler.sendMessage(msg);
		}
	}
	
	class postEditMessage4netease extends Thread {
		private String msg4netease = "";
		private String t = "";
		private String s = "";
		private String img = "";
		public postEditMessage4netease(String message, String t, String s, String img) {

			this.msg4netease = message;
			this.t = t;
			this.s = s;
			this.img = img;
		}
		@Override
		public void run() {

			Message msg = new Message();
			msg.what = 1;
			
			try {
			    msg4netease = msg4netease + getShortUrl();
				System.setProperty("tblog4j.oauth.consumerKey", WeiboLogin.neteaseCustomKey);
		    	System.setProperty("tblog4j.oauth.consumerSecret", WeiboLogin.neteaseCustomSecrect);
		    	System.setProperty("tblog4j.debug", "false");

				TBlog tblog = new TBlog();
		    	
				String host = Tools.getHostbyWAP(ShareToMicroBlog.this);
				if(null!=host){
				    tblog.setHttpProxy(host, 80);
				}
				
				tblog.setToken(t, s);

				// 发微博
				tblog.updateStatus(msg4netease);
	
				
				msg.arg1 = 0;
			} catch (TBlogException e1) {
				
				Log.e("sharetomicroblog", e1.toString());
				
				String errorinfo = e1.toString();
				
				if(errorinfo.contains("200 OK")){
					
				}else{
					msg.arg1 = 1;
				}
				
			}
			
			reflashormoreDataHandler.sendMessage(msg);
			
		}
	}
	
	class postEditMessage4QQ extends Thread {
		private String msg4QQ = "";
		private String t = "";
		private String s = "";
		private String img = "";
		public postEditMessage4QQ(String message, String t, String s, String img) {
			this.msg4QQ = message;
			this.t = t;
			this.s = s;
			this.img = img;
		}
		@Override
		public void run() {
			// TODO Auto-generated method stub
			Message msg = new Message();
			msg.what = 1;
			
			try {
				QWeiboSyncApi api = new QWeiboSyncApi();
				msg4QQ = msg4QQ + getShortUrl();
				String customKey = WeiboLogin.qqCustomKey;
				String customSecrect = WeiboLogin.qqCustomSecrect;
				String response = "";
				
				if(img != null && !img.equals("") && PicUtil.isLocalPicExit(img)) {
					response = api.publishMsg(customKey, customSecrect, t, s, msg4QQ, 
							 PicUtil.phototempDir + img, ResultType.ResultType_Json);
				} else {
					response = api.publishMsg(customKey, customSecrect, t, s, msg4QQ, 
					    		"", ResultType.ResultType_Json);
				}
				if(response != null) {
					JSONObject jobj = new JSONObject(response);
					if(jobj.getString("msg").equals("ok")) {
						msg.arg1 = 0;
					}
					else if(jobj.getString("msg").equals("check sign error")) {
						msg.what = 5;
						msg.arg1 = 1;
					}
					else if(jobj.getString("errcode").equals("13")) {
						msg.what = 4;
					}
					else if(jobj.getString("errcode").equals("0")) {
						msg.arg1 = 0;
					}
					else {
						msg.arg1 = 1;
					}
				} else {
					msg.arg1 = 1;
				}

			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
				msg.arg1 = 1;
			}
		   
			
			reflashormoreDataHandler.sendMessage(msg);
		}
	}
	
	class postEditMessage4Renren extends Thread {
	    private String msg4Renren = "";
        private String t = "";
        private String s = "";
        private String img = "";
        public postEditMessage4Renren(String message, String t, String s, String img) {
            this.msg4Renren = message;
            this.t = t;
            this.s = s;
            this.img = img;
        }
	    @Override
	    public void run(){
	        Message msg = new Message();
            msg.what = 1;
            msg.arg1 = 1;
	        try {
	            String shorturl = getShortUrl();
	            msg4Renren = msg4Renren + shorturl;
	            Logger.i("img:"+img);
	            if(null==img || "".equals(img)){
	                img = shorturl;
	            }
                ShareSetResponseBean response = mRenren.publishShare(new ShareSetRequestParam(img, msg4Renren));
                if(response != null) {
                    int r = response.getResult();
                    if(r == ShareSetResponseBean.RESULT_OK) {
                        msg.arg1 = 0;
                    }
                   
                } else {
                   
                }
            } catch (RenrenException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (Throwable e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            
            reflashormoreDataHandler.sendMessage(msg);
	    }
	}
	
	class postEditMessage4Ydnote extends Thread {
		private String title;
		private String content;
		private String source;
        private String token;
        private String tokenSecret;
        public postEditMessage4Ydnote(String title, String content, String source, String token, String tokenSecret) {
            this.title = title;
            this.content = content;
            this.source = source;
            this.token = token;
            this.tokenSecret = tokenSecret;
        }
	    @Override
	    public void run(){
	        Message msg = new Message();
            msg.what = 1;
            msg.arg1 = 1;
	        try {
	            String temppicurl = getShortUrl();
	            content = content.replace("<--insert-->", temppicurl) + shareend;
	            YdNoteLoginHelper ydnoteHelper = new YdNoteLoginHelper();
	        	OAuthAccessor accessor = ydnoteHelper.getOAuthAccess();
	            accessor.tokenSecret = tokenSecret;
	            Properties oauthInfo = new Properties();
	            oauthInfo.setProperty("oauth_token", token);
	            
	            // 获取笔记路径
	            String notebook = set_prefs.getString(YdNoteLoginHelper.YDNOTE_DEFAULT_NOTEBOOK_PAHT, null);
	            
	            HttpResponse response = null;
	            if(TextUtils.isEmpty(notebook)){
		            response = OAuthHelper.requestPostUrlEncode(ydnoteHelper.getHttpClient(),
		            		YdNoteLoginHelper.getBaseUrl() + YdNoteLoginHelper.allNotebookurl, accessor, oauthInfo, new Properties());
		            
		            String responseNoteBookStr = EntityUtils.toString(response.getEntity(), "utf-8");
		            
		            // parse the default notebook path
		            JSONArray jsonArray = new JSONArray(responseNoteBookStr);
		            JSONObject json = jsonArray.getJSONObject(0);
		            // default notebook path
		            notebook = (String)json.get("path");
		            set_prefs.edit().putString(YdNoteLoginHelper.YDNOTE_DEFAULT_NOTEBOOK_PAHT, notebook).commit();
		            response = null;
	            }
	            
	            Properties postParams = new Properties();
	            postParams.put("notebook", notebook);
	            postParams.put("source", source);
	            postParams.put("title",  title);
	            postParams.put("content", content);
	            
	            response = OAuthHelper.requestPostMultiPart(ydnoteHelper.getHttpClient(), 
	            		YdNoteLoginHelper.getBaseUrl() + YdNoteLoginHelper.createNoteurl, accessor, oauthInfo, postParams);
	            
	            String responseStr = EntityUtils.toString(response.getEntity(), "utf-8");
	            
	            // 解析responseStr 判断是否分享成功
	            JSONObject obj = new JSONObject(responseStr);
	            if(null != obj && !obj.isNull("path") && obj.getString("path").length() > 0){
	            	msg.arg1 = 0;
	            }
	        	
            } catch (Exception e) {
                e.printStackTrace();
            } 
            
            reflashormoreDataHandler.sendMessage(msg);
	    }
	}
	
	public static byte[] readFileImage(String filename)throws IOException{
		BufferedInputStream bufferedInputStream=new BufferedInputStream(
				new FileInputStream(filename));
		int len =bufferedInputStream.available();
		byte[] bytes=new byte[len];
		int r=bufferedInputStream.read(bytes);
		if(len !=r){
			bytes=null;
			throw new IOException("读取文件不正确");
		}
		bufferedInputStream.close();
		return bytes;
	}
	
	Handler reflashormoreDataHandler = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			
			switch (msg.what) {
			
			case 1:// 分享到微博
				break;
			case 2:

				do_postmicroblog_button.setEnabled(true);
				if(sharetype==3){
				    edit_postmessage.setText(message +shareend);
				}else if (sharetype==4){
					messageyd = messageyd.replace("<--insert-->", picurl) + shareend;
					edit_postmessage.setText(message);
				}else{
					edit_postmessage.setText(message + picurl +shareend);
				}
				
				message = edit_postmessage.getText().toString();
				int length = 0;
				if(sharetype == 0) {
					length = limit1-message.length();
				} else {
					length = limit2-message.length();
				}
				if(length < 0) {
					leave_size3.setText("已超出");
					leave_size.setText(String.valueOf(length*-1));
				} else {
					leave_size3.setText("还可输入");
					leave_size.setText(String.valueOf(length));
				}
				
				break;
			case 3:
				do_postmicroblog_button.setEnabled(true);
				edit_postmessage.setText(message);
				length = 0;
				if(sharetype == 0) {
					length = limit1-message.length();
				} else {
					length = limit2-message.length();
				}
				if(length < 0) {
					leave_size3.setText("已超出");
					leave_size.setText(String.valueOf(length*-1));
				} else {
					leave_size3.setText("还可输入");
					leave_size.setText(String.valueOf(length));
				}
				break;
			case 4:
				do_postmicroblog_button.setEnabled(true);
				MyToast.makeText(app, "分享的内容与上次重复",MyToast.LENGTH_SHORT).show();
				break;
			case 5:
				do_postmicroblog_button.setEnabled(true);
				MyToast.makeText(app, "分享微博失败，请重新绑定帐号",MyToast.LENGTH_SHORT).show();
				
		     
		        if(msg.arg1 == 0)  db.execSQL("delete from " + NewsSQLiteOpenHelper.OAUTH_TABLE+ " where " 
		    	        + NewsSQLiteOpenHelper.OAUTH_TYPE + "='sina'");
		        else db.execSQL("delete from " + NewsSQLiteOpenHelper.OAUTH_TABLE+ " where " 
		    	        + NewsSQLiteOpenHelper.OAUTH_TYPE + "='qq'");
				
	        	Intent intent = new Intent(ShareToMicroBlog.this, AccountSettingActivity.class);
	        	startActivity(intent);
				break;
			case 6:
                initAccount();
                break;
			}
		}
	};
	
	//异常处理提示
	Handler httpHandler = new Handler() {
		public void handleMessage(Message msg) {
			String errorinfo = msg.getData().getString("errorinfo");
			
				MyToast.makeText(app, errorinfo,MyToast.LENGTH_SHORT).show();

		}
	};
	
	private void setDefaultTips(){
	    if(Tools.CheckNetwork(app)){
	        MyToast.makeText(app, "已发送", MyToast.LENGTH_SHORT).show();
	    }else{
	        MyToast.makeText(app, "网络不可用", MyToast.LENGTH_SHORT).show();
	    }
	}
		
	public void goBackClick(View view){
        finish();
    }
	
	@Override
    public void onApplyTheme() {
        super.onApplyTheme();
        ThemeSettingsHelper themeSettingsHelper = getThemeSettingsHelper();
        themeSettingsHelper.setViewBackgroud(this, R.id.whole_space, R.drawable.loginbg);
        themeSettingsHelper.setViewBackgroud(this, R.id.top_space, R.drawable.top_background);
        themeSettingsHelper.setTextViewColor(this, R.id.share_wb_title, R.color.main_title_color);
        themeSettingsHelper.setViewBackgroud(this, do_postmicroblog_button, R.drawable.netease_big_button);
        themeSettingsHelper.setTextViewColor(this, do_postmicroblog_button, R.color.list_title_color);
        themeSettingsHelper.setImageViewSrc(this, R.id.go_back_common_btn, R.drawable.go_back);
        
    }

}
